package com.shareach.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.google.common.collect.ImmutableMap;
import com.shareach.common.BaseQueryOrder;
import com.shareach.common.BizCondition;
import com.shareach.dao.redis.impl.DeployRDao;
import com.shareach.dao.redis.impl.DeployRDao.DeployType;
import com.shareach.dao.redis.impl.MatchRDao;
import com.shareach.domain.BaseBankDomain;
import com.shareach.domain.BaseCategoryDomain;
import com.shareach.domain.BaseCityDomain;
import com.shareach.domain.BaseShopDomain;
import com.shareach.domain.BizActivityDomain;
import com.shareach.domain.BizActivityShopDomain;
import com.shareach.service.BaseBankService;
import com.shareach.service.BaseCategoryService;
import com.shareach.service.BaseCityService;
import com.shareach.service.BaseShopService;
import com.shareach.service.BizActivityService;
import com.shareach.service.BizActivityShopService;
import com.shareach.util.JsonUtil;
import com.shareach.web.basic.Answer;
import com.shareach.web.util.ParseExcelUtil;

/**
 * create time：2013-2-1 下午5:55:33
 * 
 * @author retryu
 * @since JDK 1.6
 * @version 1.0 description：
 */
@Controller("wactivity")
@RequestMapping("/wactivity")
public class ActivityController extends BaseController {

	@Autowired
	private BaseShopService shopService;

	@Autowired
	private BizActivityService activityService;

	@Autowired
	private BizActivityShopService activityShopService;

	@Autowired
	private BaseCityService cityService;

	@Autowired
	private BaseCategoryService categoryService;
	@Autowired
	BaseBankService bankService;

	@Autowired
	private MatchRDao matchRDao;
	@Autowired
	private DeployRDao deployRDao;

	public static void main(String[] args) {
		String s = DeployType.ShopBrand.getDesc();
		System.out.println(s);
	}

	@RequestMapping(value = "/index.htm")
	public ModelAndView summary(HttpServletRequest request, Long bankId, Long id, Integer hasdeploy) {
		ModelAndView mv = new ModelAndView("admin/discount/activity/index");
		Integer pageNo = this.getData(request, "pn", 1);
		Integer pageSize = this.getData(request, "ps", 1);
		String title = this.getString(request, "title", nullString, true);
		Long cityId = this.getData(request, "city", nullLong);
		String start=this.getString(request, "start", nullString,true);
		if (pageNo < 1)
			pageNo = 1;
		if (pageSize <= 1) {
			pageSize = defaultPageSize;
		}
		BizActivityDomain query = new BizActivityDomain();
		query.setCity(cityId);
		query.setTitle(title);
		addCriteria(query, hasdeploy, "deployTime");

		if (null != bankId && -1 != bankId) {
			query.setBankId(bankId);
		}
		if (null != id) {
			query.setId(id);
		}

		BaseQueryOrder order = new BaseQueryOrder();
		order.setNumber(pageNo.toString());
		order.setPageSize(pageSize);
		Page<BizActivityDomain> result = activityService.getPageResult(query, order);
		List<BaseCityDomain> cities = cityService.findAll();
		List<BaseBankDomain> banks = bankService.findAll();

		mv.addObject("conditions", ImmutableMap.of("bankId", null == bankId ? -1 : bankId));
		mv.addObject("banks", banks);
		mv.addObject("cities", cities);
		mv.addObject("result", result);
		mv.addObject("title", title);
		mv.addObject("id", id);
		mv.addObject("cityId", cityId);
		mv.addObject("deploy", hasdeploy);
		mv.addObject("start",start);
		return mv;
	}

	@RequestMapping(value = "/activityShopes.htm")
	public ModelAndView activityShop(HttpServletRequest request, Long id, Integer hasdeploy, Integer hasmatch,
			String name) {
		ModelAndView mv = new ModelAndView("admin/discount/activity/activityShopes");
		Long activityId = this.getData(request, "activityId", nullLong);
		Long cityId = this.getData(request, "cityId", nullLong);
		Integer pageNo = this.getData(request, "pn", 1);
		if (pageNo < 1)
			pageNo = 1;
		BizActivityDomain activity = new BizActivityDomain();
		BizActivityShopDomain query = new BizActivityShopDomain();
		query.setActivityId(activityId);
		addCriteria(query, hasdeploy, "deployTime");
		addCriteria(query, hasmatch, "shopId");
		if (activityId != null) {
			activity = activityService.getById(activityId);
			mv.addObject("activity", activity);
		}
		if (null != id) {
			query.setId(id);
		}
		if (null != cityId) {
			query.setCity(cityId);
		}

		if (StringUtils.isNotEmpty(name)) {
			mv.addObject("name", name);
			query.addRegexMap(name, new String[] { "name", "brandName" });
		}
		BaseQueryOrder order = new BaseQueryOrder();
		order.setNumber(pageNo + "");
		order.setPageSize(defaultPageSize);
		Page<BizActivityShopDomain> result = activityShopService.getPageResult(query, order);

		List<BizActivityShopDomain> domainList = result.getContent();
		for (BizActivityShopDomain activityShop : domainList) {
			if (activityShop.getShopId() != null && activityShop.getShopId() > 0) {
				activityShop.setBaseShop(shopService.getById(activityShop.getShopId()));
			}
		}

		List<BaseCityDomain> cities = cityService.findAll();
		mv.addObject("result", result);
		mv.addObject("cities", cities);
		mv.addObject("cityId", cityId);
		mv.addObject("activityId", activityId);
		mv.addObject("id", id);
		mv.addObject("deploy", hasdeploy);
		mv.addObject("match", hasmatch);
		return mv;
	}

	@RequestMapping(value = "/shopes.htm")
	public ModelAndView shopes(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("admin/discount/activity/shopes");
		BaseShopDomain query = new BaseShopDomain();

		Long id = this.getData(request, "id", nullLong);
		Long cityId = this.getData(request, "city", nullLong);
		Long categotyId = this.getData(request, "category", nullLong);
		if (cityId != null) {
			query.setCity(cityId);
		}
		if (categotyId != null) {
			query.setCategory(categotyId);
		}
		String name = this.getString(request, "name", nullString, true);

		query.setName(name);
		Page<BaseShopDomain> result = shopService.getPageResult(query, null);
		List<BaseCityDomain> cities = cityService.findAll();
		BaseCategoryDomain cquery = new BaseCategoryDomain();
		List<BaseCategoryDomain> categorys = categoryService.getList(cquery);
		mv.addObject("cities", cities);
		mv.addObject("city", cityId);
		mv.addObject("categories", categorys);
		mv.addObject("category", categotyId);
		mv.addObject("result", result);
		mv.addObject("id", id);
		return mv;
	}

	@RequestMapping(value = "/upload.do")
	public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request) {

		ModelAndView mv = new ModelAndView(new RedirectView("index.htm"));
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {

			String fileName = file.getOriginalFilename();
			if (fileName == null)
				return mv;

			String path = request.getSession().getServletContext().getRealPath("/upload") + "//";
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdir();
			}
			// 读取文件流并保持在指定路径
			inputStream = file.getInputStream();
			outputStream = new FileOutputStream(path + file.getOriginalFilename());
			byte[] buffer = file.getBytes();
			// int bytesum = 0;
			int byteread = 0;
			while ((byteread = inputStream.read(buffer)) != -1) {
				// bytesum += byteread;
				outputStream.write(buffer, 0, byteread);
				outputStream.flush();
			}
			outputStream.close();
			inputStream.close();
			String fullFileName = path + file.getOriginalFilename();
			parseExcel(new File(fullFileName));

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != inputStream) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != outputStream) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return mv;
	}

	@RequestMapping(value = "/uploadImg.do")
	public ModelAndView uploadImg(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request) {

		ModelAndView mv = new ModelAndView(new RedirectView("index.htm"));

		String title = getString(request, "title", nullString, true);
		BizActivityDomain query = new BizActivityDomain();
		query.setTitle(title);
		List<BizActivityDomain> activities = activityService.getList(query);

		String path = request.getSession().getServletContext().getRealPath("/upload");
		saveActivityImg(file, activities, path);
		return mv;

	}

	private void saveActivityImg(MultipartFile file, List<BizActivityDomain> activities, String path) {
		try {
			InputStream inputStream = file.getInputStream();

			String suffix = "." + file.getContentType().split("/")[1];
			String fileName = "" + System.currentTimeMillis() + suffix;
			OutputStream outputStream = new FileOutputStream(path + "/" + fileName);
			byte[] buffer = file.getBytes();
			// int bytesum = 0;
			int byteread = 0;
			while ((byteread = inputStream.read(buffer)) != -1) {
				// bytesum += byteread;
				outputStream.write(buffer, 0, byteread);
				outputStream.flush();
			}
			outputStream.close();
			inputStream.close();
			for (BizActivityDomain activity : activities) {
				activity.setImg(fileName);
				activityService.update(activity, new BizCondition().put("id", activity.getId()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/info.htm")
	public ModelAndView info(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("admin/discount/activity/info");
		Long activityId = getData(request, "activityId", nullLong);
		BizActivityDomain activity = activityService.getById(activityId);
		mv.addObject("activity", activity);
		return mv;
	}

	@RequestMapping(value = "/match.htm")
	public void mactch(HttpServletRequest request) {
		Long id = getData(request, "id", nullLong);
		Long shopId = getData(request, "shopId", nullLong);
		if (id == null || shopId == null)
			return;
		BizActivityShopDomain shop = activityShopService.getById(id);
		shop.setShopId(shopId);
		activityShopService.update(shop, new BizCondition().put("_id", shop.getId()));
	}

	@RequestMapping(value = "/edit.htm")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, String activityId,
			BizActivityDomain domain) {
		ModelAndView view = new ModelAndView("admin/discount/activity/edit");
		if (domain == null || domain.getId() == null) {
			// redirect
			Long parabrand = Long.valueOf(activityId);
			BizActivityDomain activity = activityService.getById(parabrand);
			view.addObject("activity", activity);
			return view;
		} else {
			Answer<Object> r = new Answer<Object>();
			try {
				BizActivityDomain activity = activityService.getById(domain.getId());
				BizActivityDomain change = activity.compareTo(domain);
				change.setId(domain.getId());
				// edit
				activityService.update(change);
				// update redis
				resetRedisDeployed(DeployType.Activity, domain.getId());
				this.outText(response, JsonUtil.jsonFromObject(r));
			} catch (Exception e) {
				r.setCode(-1);
				r.setMsg("System Error");
				this.outText(response, JsonUtil.jsonFromObject(r));
				e.printStackTrace();
			}
		}
		return view;
	}

	@RequestMapping(value = "/editShop.htm")
	public ModelAndView editShop(HttpServletRequest request, HttpServletResponse response, String activityShopId,
			BizActivityShopDomain domain) {
		ModelAndView view = new ModelAndView("admin/discount/activity/editShop");
		if (domain == null || domain.getId() == null) {
			// redirect
			Long parabrand = Long.valueOf(activityShopId);
			BizActivityShopDomain activityShop = activityShopService.getById(parabrand);
			view.addObject("activityShop", activityShop);
			return view;
		} else {
			Answer<Object> r = new Answer<Object>();
			try {
				BizActivityShopDomain activityShop = activityShopService.getById(domain.getId());
				BizActivityShopDomain change = activityShop.compareTo(domain);
				change.setId(domain.getId());
				// edit
				activityShopService.update(change);
				// update redis
				resetRedisDeployed(DeployType.ActivityShop, domain.getId());
				this.outText(response, JsonUtil.jsonFromObject(r));
			} catch (Exception e) {
				r.setCode(-1);
				r.setMsg("System Error");
				this.outText(response, JsonUtil.jsonFromObject(r));
				e.printStackTrace();
			}
		}
		return view;
	}

	public void parseExcel(File file) {
		new ParseExcelUtil(file, activityService, activityShopService, cityService, matchRDao, deployRDao);
	}

	private void addCriteria(BizActivityShopDomain domain, Integer val, String propName) {
		if (null == val) {
			return;
		}
		switch (val) {
		case 2:
			domain.addFieldExists(propName);
			break;
		case 3:
			domain.addFieldNoneExists(propName);
			break;
		}
	}

	private void addCriteria(BizActivityDomain domain, Integer val, String propName) {
		if (null == val) {
			return;
		}
		switch (val) {
		case 2:
			domain.addFieldExists(propName);
			break;
		case 3:
			domain.addFieldNoneExists(propName);
			break;
		}
	}

	public void resetRedisDeployed(DeployType type, Long id) {
			deployRDao.setUndeployed(type, id);
	}
}
